
#import "DocumentViewController.h"
#import "NSString+VoiceOver.h"
#import <MessageUI/MFMailComposeViewController.h>

@interface DocumentViewController() <UIWebViewDelegate, MFMailComposeViewControllerDelegate> {
    NSMutableArray *documentNames;
    NSMutableArray *webViews;
}

@property (nonatomic, strong) UIWebView *currentWebView;

@end


@implementation DocumentViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.edgesForExtendedLayout = UIRectEdgeNone;
}

-(NSString *)loadDocumentWithName:(NSString *)documentName
{
    NSString *locale = @"sv";
    NSString *file = [locale stringByAppendingFormat:@"_%@", documentName];
    NSLog(@"%@", file);
    NSString *html = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] 
                                                         pathForResource:file
                                                         ofType:@"html"] 
                                               encoding:NSUTF8StringEncoding error:nil];
    html = [html stringByReplacingOccurrencesOfString:@"../" withString:@""];
    html = [html stringByReplacingOccurrencesOfString:@".png" withString:@"@2x.png"];
    html = [html stringByReplacingOccurrencesOfString:@"Energimarkning-Lampa@2x.png" withString:@"Energimarkning-Lampa.png"];
    html = [html stringByReplacingOccurrencesOfString:@"Energimarkning-Armatur@2x.png" withString:@"Energimarkning-Armatur.png"];

    return html;
}

-(void)showDocumentWithName:(NSString *)documentName
{
    [self showDocumentWithName:documentName andHtml:[self loadDocumentWithName:documentName]];
}

-(void)showDocumentWithName:(NSString *)documentName andHtml:(NSString *)html
{
    [self view]; // Force load of view
    
    if (!documentNames) {
        documentNames = [NSMutableArray array];
        webViews = [NSMutableArray array];
    }
    NSInteger index = [documentNames indexOfObject:documentName];
    UIWebView *currentWebView;
    if (index == NSNotFound) {
        currentWebView = [[UIWebView alloc] initWithFrame:self.view.bounds];
        currentWebView.backgroundColor = kBackgroundColor;
        currentWebView.dataDetectorTypes = UIDataDetectorTypeNone;
        currentWebView.delegate = self;
        currentWebView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        
        [documentNames addObject:documentName];
        [webViews addObject:currentWebView];

        [self.view addSubview:currentWebView];
        if (voiceoverEnabled) {
            html = [html stringByOptimizingForVoiceOver];
        }
        [currentWebView loadHTMLString:html baseURL:[[NSBundle mainBundle] bundleURL]];
        self.currentWebView = currentWebView;
    } else {
        self.currentWebView = webViews[index];
        [self.currentWebView.scrollView setContentOffset:CGPointZero animated:NO];
    }
    
    
    for (UIWebView *webView in webViews) {
        webView.alpha = webView == self.currentWebView ? 1.0 : 0.0;
    }
}

- (void)userSwipedRight:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)sendMailTo:(NSString *)mailTo
{
    NSArray *chunks = [mailTo componentsSeparatedByString:@":"];
    
    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate = self;
    
    NSArray *toRecipients = @[chunks[1]];
    [picker setToRecipients:toRecipients];
    
    [self.parentViewController.parentViewController presentViewController:picker animated:YES completion:nil];
}


#pragma mark - Web view delegate
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if (navigationType != UIWebViewNavigationTypeLinkClicked) {
        return YES;
    } else {
        NSString *urlString = [[request URL] absoluteString];
        NSLog(@"urlString: %@", urlString);
        if ([urlString rangeOfString:@"mailto"].location != NSNotFound) {
            [self sendMailTo:urlString];
        } else {
            [[UIApplication sharedApplication] openURL:[request URL]];
        }
        return NO;
    }
}


#pragma mark - Mail composer delegate
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
    NSString *message = nil;
    switch (result)
    {
        case MFMailComposeResultSaved:
            message = _(@"Ditt e-postmeddelandet sparat");
            break;
        case MFMailComposeResultSent:
            message = _(@"Ditt e-postmeddelande är skickat");
            break;
        case MFMailComposeResultFailed:
            message = _(@"Misslyckades med att skicka ditt e-postmeddelande");
            break;
        default:
            break;
    }
    
    if (message != nil) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:_(@"Information") message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }

    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
